package com.gwz.cardserver.service;

import com.gwz.cardserver.consts.ChatCodeConst;
import com.gwz.cardserver.consts.ChatMessageEnums;
import com.gwz.cardserver.consts.SocketConst;
import com.gwz.cardserver.dto.ReqBase;
import com.gwz.cardserver.dto.ResBase;
import com.gwz.cardserver.dto.chat.ChatDto;
import com.gwz.cardserver.dto.room.MatchRoom;
import com.gwz.cardserver.global.GlobalCache;
import com.gwz.cardserver.global.MatchCache;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class ChatService {
    @Autowired
    private GlobalCache globalCache;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MatchCache matchCache;

    public void chatRequest(ChannelHandlerContext ctx, ReqBase reqBase) {
        Assert.isTrue(accountService.isOnline(ctx), ResBase.fall(reqBase, "玩家不在线"));
        String userId = globalCache.getUserIdBYChannel(ctx);
        int chatType = Integer.parseInt(reqBase.getMessage());

        ChatDto chatDto = ChatDto.builder().userId(userId).chatType(chatType).text(ChatMessageEnums.getByCode(chatType).getValue()).build();

        if (matchCache.isMatching(userId)) {
            MatchRoom room = matchCache.getRoom(userId);
            ResBase resBase = new ResBase();
            resBase.setCode(SocketConst.CHAT);
            resBase.setSubCode(ChatCodeConst.DEFAULT);
            resBase.setResCode(200);
            resBase.setResult(chatDto);
            room.brocast(resBase, null);
        }

    }
}
